package biz

import (
	"beetle/internal/model"
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"strconv"
)

// initRedisClient 初始化Redis客户端
func initRedisClient(setting *model.RedisSetting) *redis.Client {
	return redis.NewClient(&redis.Options{
		Addr:     setting.Host + ":" + strconv.Itoa(setting.Port),
		Password: setting.Password,
		DB:       setting.DB,
	})

}

// refresh 刷新缓存数据
func refresh(client *redis.Client, key string, data string) error {

	if data == "" {
		// 如果缓存数据为空就不操作
		return nil
	}

	_, err := client.Del(context.Background(), key).Result()
	if err != nil {
		return err
	}

	_, err = client.Set(context.Background(), key, data, 0).Result()
	return err

}

// remove 删除缓存
func remove(client *redis.Client, key string) error {

	_, err := client.Del(context.Background(), key).Result()
	return err

}

// push推送多个值到redis中
func push(client *redis.Client, mp map[string]string) error {

	if len(mp) == 0 {
		return nil
	}

	var err error
	for k, v := range mp {
		tempErr := refresh(client, k, v)
		if tempErr != nil {
			err = fmt.Errorf("缓存%v刷新失败:%v,%w", k, tempErr, err)
		}
	}

	return err
}
